package com.fzs.sshd.cli.server.listener;

import com.fzs.sshd.cli.server.session.SessionManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.sshd.common.session.Session;
import org.apache.sshd.common.session.SessionListener;

@Slf4j
public class ADBSessionListener implements SessionListener {

    @Override
    public void sessionDisconnect(Session session, int reason, String msg, String language, boolean initiator) {
        //只有用户主动断开的情况会监听到
        log.info("sessionDisconnect:{}", session.getUsername());
    }

    @Override
    public void sessionCreated(Session session) {
        //在这里统计不合适
        log.info("sessionCreated:{}", session.getUsername());
    }

    @Override
    public void sessionEvent(Session session, Event event) {
        log.info("sessionEvent:{},user:{}", event, session.getUsername());
        if (event == Event.Authenticated){
            SessionManager.sessionCountMap.compute(session.getUsername(), (k, v) -> {
                if (v == null) {
                    return 1; // 不存在时，初始化计数为1
                }
                return v + 1; // 存在时，计数加1
            });
        }
    }

    @Override
    public void sessionClosed(Session session) {
        SessionManager.sessionCountMap.compute(session.getUsername(), (k, v) -> {
            if (v == null || v <= 1) {
                return null; // 不存在或只剩一个连接时，删除key
            }
            return v - 1; // 存在多个连接时，计数减1
        });
        log.info("sessionClosed:{}", session.getUsername());
    }

}
